package com.ztjava.common.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.xiaoleilu.hutool.date.DateField;
import com.xiaoleilu.hutool.date.DateUtil;
import com.ztjava.common.model.push.PushCaptcha;
import com.ztjava.common.model.push.PushRecord;
import com.ztjava.common.model.push.PushTemplate;
import com.ztjava.common.tool.push.PushInterface;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseService;
import com.ztjava.core.bean.sub.CaptchaBean;
import com.ztjava.core.bean.sub.PushBean;
import com.ztjava.core.client.Client;
import com.ztjava.core.utiliy.StringUtil;

public class PushService extends BaseService{
	private static Logger logger = Logger.getLogger(PushService.class);
	private Map<String,PushInterface> interfaceMap = new HashMap<String, PushInterface>();
	
	/***
	 * 推送信息
	 * @param ret
	 * @return
	 */
	public Ret push(PushBean pushBean){
		Cache cache = Redis.use();
		if(!cache.exists(Constant.R_PRE+"COMMON_PUSH_TEMPLATE")){
			return Ret.create(Constant.RESULT,Constant.ERROR).set(Constant.MESSAGE, "推送模板缓存不存在！");
		}
		String code = pushBean.getCode();
		if(code==null||code.equals("")||!cache.hexists(Constant.R_PRE+"COMMON_PUSH_TEMPLATE", code)){
			return Ret.create(Constant.RESULT,Constant.ERROR).set(Constant.MESSAGE, "推送模板编码不存在！");
		}
		PushTemplate pushTemplate = cache.hget(Constant.R_PRE+"COMMON_PUSH_TEMPLATE", code);
		if(pushTemplate.getStr("enable_flag").equals(Constant.F)){
			return Ret.create(Constant.RESULT,Constant.ERROR).set(Constant.MESSAGE, "推送模板已停用！");
		}
		PushInterface pushInterface = interfaceMap.get(pushTemplate.getStr("api"));
		if(pushInterface==null){
			try{
				pushInterface = (PushInterface)Class.forName(pushTemplate.getStr("api")).newInstance();
				interfaceMap.put(pushTemplate.getStr("api"), pushInterface);
			}catch (Exception e){
				e.printStackTrace();
				return Ret.create(Constant.RESULT,Constant.ERROR).set(Constant.MESSAGE, "推送接口实现失败！");
			}
		}
		if(pushBean.getTo()==null||pushBean.getTo().equals("")){
			return Ret.create(Constant.RESULT,Constant.ERROR).set(Constant.MESSAGE, "未配置接收人！");
		}
		PushRecord pushRecord = new PushRecord();
		pushRecord.set("model", pushBean.getModel());
		pushRecord.set("from", pushBean.getFrom());
		pushRecord.set("to", pushBean.getTo());
		pushRecord.set("template_id",pushTemplate.getInt("id"));
		pushRecord.set("create_user",pushBean.getCreate_user());
		String content = pushTemplate.getStr("content");
		//模板参数匹配
		if(pushBean.getParams()!=null&&pushBean.getParams().length>0){
			for(String[] item:pushBean.getParams()){
				content = content.replace("{"+item[0]+"}", item[1]);
			}
		}
		pushRecord.set("content", content);
		Ret pushResult = pushInterface.push(pushBean.getTo(),content);
		pushRecord.set(Constant.RESULT,pushResult.getStr(Constant.RESULT));
		pushRecord.set(Constant.MESSAGE,pushResult.getStr(Constant.MESSAGE));
		if(pushTemplate.getStr("is_record").equals(Constant.T)) pushRecord.save();
		return pushResult;
	}
	
	/***
	 * 模板缓存
	 */
	public void loadTemplateCache(){
		Cache cache = Redis.use();
		cache.del(Constant.R_PRE+"COMMON_PUSH_TEMPLATE");
		List<PushTemplate> templateList = PushTemplate.dao.find("select * from "+PushTemplate.tablename+" order by id asc");
		for(PushTemplate item:templateList){
			cache.hset(Constant.R_PRE+"COMMON_PUSH_TEMPLATE", item.getStr("code"), item);
		}
		logger.info(Constant.R_PRE+"COMMON_PUSH_TEMPLATE缓存加载完成！");
	}
	/*************
	 *Template分页
	**************/
	public Page<PushTemplate> getTemplatePage(Client client,Map<String,String[]> paramMap){
		String[][] param = new String[][]{
			new String[]{"name",like,"name"}
									,new String[]{"code",like,"code"}
									,new String[]{"is_record",eq,"is_record"}
									,new String[]{"enable_flag",eq,"enable_flag"}
						};
		Page<PushTemplate> pd = PushTemplate.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1), 
				getParaToInt(paramMap,client.getPageSize(),20),
				"select *","from "+PushTemplate.tablename+" where 1=1 " 				
				+ whereSql(paramMap,param)
				+ orderby(client, paramMap),whereParam(paramMap, param));
		changeBasedata(pd.getList()		, new String[]{"is_record","SHIFOU"}		, new String[]{"enable_flag","ENABLE_FLAG"});
		return pd;
	}

	/*************
	 *Record分页
	**************/
	public Page<PushRecord> getRecordPage(Client client,Map<String,String[]> paramMap){
		String[][] param = new String[][]{
			new String[]{"template_id",eq,"template_id"}
			,new String[]{"model",like,"model"}
									,new String[]{"from",like,"from"}
									,new String[]{"to",like,"to"}
									,new String[]{"content",like,"content"}
									,new String[]{"result",eq,"result"}
						};
		Page<PushRecord> pd = PushRecord.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1), 
				getParaToInt(paramMap,client.getPageSize(),20),
				"select *","from "+PushRecord.tablename+" where 1=1 " 				
				+ whereSql(paramMap,param)
				+ orderby(client, paramMap),whereParam(paramMap, param));
		changeBasedata(pd.getList()		, new String[]{"result","SUCCESSERROR"});
		return pd;
	}

	/***
	 * 检查消息时间
	 * @param portal
	 * @param to
	 * @return
	 */
	public boolean checkMessageTime(String portal,String to,int second){
		PushCaptcha pushCaptcha = PushCaptcha.dao.findFirst("select * from "+PushCaptcha.tablename+" where portal=? and `to`=? and create_time>?",
				portal,to,DateUtil.offset(new Date(), DateField.SECOND,-second));
		if(pushCaptcha==null){
			return true;
		}
		return false;
	}
	//检查验证信息
	public Ret checkMessageCaptcha(CaptchaBean captchaBean){
		Ret ret = new Ret();
		PushCaptcha pushCaptcha = PushCaptcha.dao.findFirst("select * from "+PushCaptcha.tablename
				+" where portal=? and `to`=? and auth_type=? and create_time>? and is_use='F' order by id desc",
				captchaBean.getPortal(),captchaBean.getTo(),captchaBean.getAuth_type(),DateUtil.offsetMinute(new Date(), -10));
		if(pushCaptcha==null){
			ret.set(Constant.RESULT, Constant.ERROR);
			ret.set(Constant.MESSAGE, "验证信息不可用！");
			return ret;
		}
		if(!pushCaptcha.getStr("captcha").equals(captchaBean.getCaptcha())){
			ret.set(Constant.RESULT, Constant.ERROR);
			ret.set(Constant.MESSAGE, "验证码不正确！");
			return ret;
		}
		ret.set(Constant.RESULT, Constant.SUCCESS);
		ret.set(Constant.MESSAGE, "验证通过！");
		pushCaptcha.set("is_use", "T").update();
		return ret;
	}
	/***
	 * 检查消息数量
	 * @param portal
	 * @param to
	 * @param hour
	 * @param maxTimes
	 * @return
	 */
	public boolean checkMessageCount(String portal,String to,int hour,int maxTimes){
		long times = Db.queryInt("select count(id) from "+PushCaptcha.tablename
				+" where portal=? and  `to`=? and create_time>?",
				portal,to,DateUtil.offset(new Date(), DateField.HOUR, -hour).toTimestamp());
		if(times<maxTimes){
			return true;
		}
		return false;
	}
	/***
	 * 检查IP发送次数
	 * @param portal
	 * @param ip
	 * @param hour
	 * @param maxTimes
	 * @return
	 */
	public boolean checkMessageIpCount(String portal,String ip,int hour,int maxTimes){
		long times = Db.queryInt("select count(id) from "+PushCaptcha.tablename
				+" where portal=? and ip=? and create_time>?",
				portal,ip,DateUtil.offset(new Date(), DateField.HOUR, -hour).toTimestamp());
		if(times<maxTimes){
			return true;
		}
		return false;
	}
	/**
	 * 新建消息
	 * @param portal
	 * @param auth_type
	 * @param to
	 * @param code
	 * @param ip
	 * @return
	 */
	public String insertCaptcha (String portal,String auth_type,String to,String ip){
		PushCaptcha pushCaptcha = new PushCaptcha();
		pushCaptcha.set("portal", portal);
		pushCaptcha.set("auth_type", auth_type);
		pushCaptcha.set("to", to);
		pushCaptcha.set("captcha", StringUtil.getRandomInt(6));
		pushCaptcha.set("ip", ip);
		pushCaptcha.save();
		return pushCaptcha.getStr("captcha");
	}
}
